package cn.thr.pethome.vcode.controller;

import cn.thr.pethome.constants.BaseConstants;
import cn.thr.pethome.util.AjaxResult;
import cn.thr.pethome.util.SendMsgUtil;
import cn.thr.pethome.util.StrUtils;
import cn.thr.pethome.util.VerifyCodeUtils;
import cn.thr.pethome.vcode.domain.EmailCodeVo;
import cn.thr.pethome.vcode.domain.Vcode;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/vcode")
//这里是说明你这个类是干什么用的
@Api(value = "验证码的API",description="验证码相关的CRUD功能")
public class CodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${msg_Uid}")
    private String msg_Uid;

    @Value("${msg_Key}")
    private String msg_Key;



    @GetMapping("/imgcode/{key}")
    public AjaxResult getImgCode(@PathVariable String key){
        try {
            String code = StrUtils.getRandomString(6).toLowerCase();
            redisTemplate.opsForValue().set(key,code,3, TimeUnit.MINUTES);
            String base64Img = VerifyCodeUtils.VerifyCode(110, 40, code);
            return AjaxResult.success().setData(base64Img);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("图像码生成失败咯");
            return AjaxResult.error().setMsg("请你重新插拔网线，或者关机电脑稍后重试");
        }
    }

    @GetMapping("/imageEmailCode/{key}")
    public AjaxResult getImageEmailCode(@PathVariable("key") String key){
        try {
            //生成一个6位的随机数，当作验证码
            String code = StrUtils.getRandomString(6).toLowerCase();
            //将前端传过来的key和随机生成的验证码存入redis并且设置过期时间为3分钟
            redisTemplate.opsForValue().set(key,code,3, TimeUnit.MINUTES);
            //生成邮件注册的图片验证并且进行编码
            String base64Image = VerifyCodeUtils.VerifyCode(110, 40, code);
//            System.out.println(base64Image);
            //返回图片验证码的编码给前端
            return AjaxResult.success().setData(base64Image);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("图片验证码生成失败");
            return AjaxResult.error().setMsg("网络异常，请联系管理员");
        }
    }


    @PostMapping("/sendSmsCode")
    public  AjaxResult sendSmsCode(@RequestBody Vcode vcode){
        String imageCodeKey = vcode.getImageCodeKey();
        String phone = vcode.getPhone();
        String imageCode = vcode.getImageCode();
        //参数校验
        if ( imageCodeKey== null || "".equals(imageCodeKey.trim())){
            return AjaxResult.error().setMsg("非法访问");
        }
        if (phone == null || "".equals(phone.trim())){
            return AjaxResult.error().setMsg("手机号不能空");
        }
        if (imageCode == null || "".equals(imageCode.trim())){
            return AjaxResult.error().setMsg("验证码不能空");
        }
        //前置条件
        //验证码校验
        Object value = redisTemplate.opsForValue().get(imageCodeKey);
        System.out.println(value);
        if(value == null){//看验证码有没有失效
            return AjaxResult.error().setMsg("图片验证码已失效");
        }
        if(!value.toString().equals(imageCode)){//判断用户输入的验证码对不对
            return AjaxResult.error().setMsg("验证码输出错误!");
        }
        //手机验证
        String phoneCode = StrUtils.getRandomString(4).toLowerCase();


        String keyTime = phone+BaseConstants.Vocode.REGISTER_TIME;//获取上一次的时间
        //防止重发
        Object o = redisTemplate.opsForValue().get(keyTime);//取时间
        if (o == null){ //如果O等于空就发送验证码
            //添加业务标识
            long starTime = System.currentTimeMillis();
            String key = phone+ BaseConstants.Vocode.REGISTER;
            redisTemplate.opsForValue().set(key,phoneCode,BaseConstants.Vocode.REGISTER_TIME_OUT,TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(keyTime,starTime,BaseConstants.Vocode.REGISTER_TIME_OUT,TimeUnit.MINUTES);
        }else {
            Long aLong = Long.valueOf(o.toString());
            Long endTime = System.currentTimeMillis(); //这个是当前时间
            if (endTime-aLong<60000){
                return AjaxResult.error().setMsg("请勿重复发验证码");
            }else {
                //重置过期时间
                String key = phone+BaseConstants.Vocode.REGISTER;
                phoneCode = (String) redisTemplate.opsForValue().get(key);
                long starTime = System.currentTimeMillis();
                redisTemplate.opsForValue().set(key,phoneCode,3,TimeUnit.MINUTES);
                redisTemplate.opsForValue().set(keyTime,starTime,3,TimeUnit.MINUTES);
            }
        }

        //发送短信验证码
        /*SendMsgUtil.sendmsg();*/
        SendMsgUtil.sendmsg(msg_Uid,msg_Key,phone,phoneCode);
        System.err.println(phoneCode);
        return AjaxResult.success().setMsg("短信发送成功");
    }
    @PostMapping("/sendEmailSmsCode")
    public AjaxResult sendEmailSmsCode(@RequestBody EmailCodeVo EmailCodeVo) {
        String imageEmailCode = EmailCodeVo.getImageEmailCode();
        String imageEmailCodeKey = EmailCodeVo.getImageEmailCodeKey();
        String email = EmailCodeVo.getEmail();
        //判断参数是否合规
        //判断图片验证码的key是否为空
        if(imageEmailCodeKey == null || "".equals(imageEmailCodeKey.trim())){
            return AjaxResult.error().setMsg("非法访问");
        }
        //判断email是否为空
        if(email == null || "".equals(email.trim())){
            return AjaxResult.error().setMsg("邮箱号不能为空");
        }
        //判断图片验证码是否为空
        if(imageEmailCode == null || "".equals(imageEmailCode.trim())){
            return AjaxResult.error().setMsg("图片验证码不能为空");
        }
        //前置条件
        Object value = redisTemplate.opsForValue().get(imageEmailCodeKey);
        //判断图形验证码是否失效
        if(value == null){
            return AjaxResult.error().setMsg("你的图片验证码已失效，请重新获取");
        }
        //判断图片验证码是否失效
        if(!imageEmailCode.equals(value.toString())){
            return AjaxResult.error().setMsg("请输入正确的图形验证码");
        }
        //获取邮箱验证码
        String emailCode = StrUtils.getRandomString(4).toLowerCase();
        //把验证码存入redis里面key为imageEmailCodeKey,值为emailCode，并设置过期时间为3分钟
        redisTemplate.opsForValue().set(imageEmailCodeKey,emailCode,BaseConstants.Vocode.REGISTER_TIME_OUT,TimeUnit.MINUTES);
        //判断邮箱是否合规

        //防止重发
        // TODO: 2023/1/13
//        if(){
//
//        }
        //发送邮件验证码
        //emailActivationUtil.register(email,emailCode);
        System.err.println(emailCode);
        return AjaxResult.success().setMsg("邮箱验证码发送成功成功,请在"+BaseConstants.Vocode.REGISTER_TIME_OUT+"分钟之内使用");
    }
}
